package demo26;

import java.util.LinkedList;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 使用Lock和Condition来实现生产者和消费者的同步容器，
 * 相比使用wait/notifyAll,使用Condition的方式能更加精确地指定哪些线程被唤醒。
 */
public class MyContainer2 {
    final private LinkedList<Object> list = new LinkedList<>();
    final private int MAX = 10;
    private int count = 0;

    private Lock lock = new ReentrantLock();
    private Condition producer = lock.newCondition();
    private Condition consumer = lock.newCondition();

    public void put(Object obj) {
        try {
            lock.lock();
            while (list.size() == MAX) {
                producer.await();
            }
            list.add(obj);
            ++count;
            consumer.signalAll(); //通知消费者进行消费
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public Object get() {
        Object obj = null;
        try {
            lock.lock();
            while (count == 0) {
                consumer.await();
            }
            obj = list.removeFirst();
            count--;
            producer.signalAll();  //通知生产者进行生产
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
        return obj;
    }

    public static void main(String[] args) {
        MyContainer2 c = new MyContainer2();
        for (int i = 0; i < 10; i++) {  //10个消费者
            new Thread(() -> {
                for (int j = 0; j < 5; j++) {  //每个消费者最多消费5个
                    System.out.println("消费者线程" + Thread.currentThread().getName() + ",开始消费： " + c.get());
                }
            }, "c" + i).start();
        }
        //启动生产者线程
        for (int i = 0; i < 2; i++) { //2个生产者
            new Thread(() -> {
                for (int j = 0; j < 25; j++) {  //每个生产者最多生产25个
                    c.put(Thread.currentThread().getName() + " " + j);
                }
            }, "p" + i).start();
        }
    }
}
